(ns tala.test.db
  (:use tala.db)
  (:use clojure.test))

(def test-database "test/data/testdb.db")
(def test-sql "test/data/testdb.sql")

(let [testdb-db  (java.io.File. test-database)
      testdb-sql (java.io.File. test-sql)]
  (when (or (not (.exists testdb-db))
            (< (.lastModified testdb-db)
               (.lastModified testdb-sql)))
    (println (str "!!! Test database " test-database " does not exist or is out of date!"))
    (println "!!! Do (cd test/data; rm -f testdb.db; ./make-testdb.sh)")
    (System/exit 1)))


(def db-sqlite
  {:classname "org.sqlite.JDBC"
   :subprotocol "sqlite"
   :subname test-database})

;; Tests basic connection to the DB -- doesn't depend on any schema
;; within the DB (and this will make an empty DB if the file doesn't exist)
(deftest test-make-query
  (is (= '(42)
         (make-query db-sqlite
                     ["select 6 * 9 - 12 as res"]
                     #(map (fn [r] (:res r)) %)))))

;; Tests making queries against the DB -- depends on the test database contents
(deftest test-get-accounts
  (is (= '("0user1")
         (make-query db-sqlite
                     ["select ident from accounts"]
                     #(map (fn [r] (:ident r)) %)))
      "Does the test database exist? (cd test/data; ./make-testdb.sh)"))
